package org.yang.common.i18n.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;

/**
 * 国际化拦截器
 *
 * @author: lslands
 * @version: 1.0
 * @create: 2024/5/10
 * @description:  request.getHeader("Accept-Language"); 判断是否需要国际化
 */
@Slf4j
public class LocaleInterceptor extends LocaleChangeInterceptor {

    private static final String LOCALE = "Accept-Language";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String newLocale = request.getHeader(LOCALE);
        if (newLocale != null) {
            LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
            if (localeResolver == null) {
                log.error("找不到LocaleResolver：不在DispatcherServlet请求中");
                throw new IllegalStateException("国际化失败");
            }
            try {
                localeResolver.setLocale(request, response, parseLocaleValue(newLocale));
            } catch (IllegalArgumentException ignore) {
                ignore.printStackTrace();
            }
        }
        return true;
    }


}
